from rest_framework import serializers
from .models import User, UserRole, Department


class DepartmentSerializer(serializers.ModelSerializer):
    """
    部门序列化器：用于处理部门信息
    """
    class Meta:
        model = Department
        fields = ['department_id', 'department_name', 'description', 'created_at', 'updated_at']


class UserSerializer(serializers.ModelSerializer):
    """
    用户序列化器：用于处理用户信息，包括关联的部门信息
    """
    department = DepartmentSerializer(read_only=True)  # 嵌套序列化部门信息
    department_id = serializers.PrimaryKeyRelatedField(
        queryset=Department.objects.all(),
        source='department',
        write_only=True,
        required=False,
        allow_null=True
    )  # 用于通过 department_id 设置部门

    class Meta:
        model = User
        fields = [
            'user_id',
            'username',
            'email',
            'password_hash',
            'employee_number',
            'department',  # 只读嵌套部门详情
            'department_id',  # 写入用字段
            'status',
            'created_at',
            'updated_at'
        ]
        extra_kwargs = {
            'password_hash': {'write_only': True},  # 隐藏密码字段
        }


class UserRoleSerializer(serializers.ModelSerializer):
    """
    用户角色序列化器：用于处理用户与角色的映射关系
    """
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=True)

    class Meta:
        model = UserRole
        fields = ['id', 'user', 'role_id', 'assigned_by', 'created_at']
